from flask import Flask, request, jsonify
from flask_cors import CORS
import requests
import os
from dotenv import load_dotenv

app = Flask(__name__)
# 启用CORS支持
CORS(app, resources={"/*": {"origins": "*"}})

# 加载环境变量
load_dotenv()

# Dify API配置
DIFY_BASE_URL = os.getenv('DIFY_BASE_URL', 'http://localhost/v1')
API_KEY = os.getenv('API_KEY', 'app-3cXStNjpVpwNBh2boIIatPyY')

@app.route('/v1/chat-messages', methods=['POST'])
def chat_messages():
    try:
        # 获取请求数据
        data = request.json
        
        # 准备请求头，添加API Key
        headers = {
            'Authorization': f'Bearer {API_KEY}',
            'Content-Type': 'application/json'
        }
        
        # 构建目标URL
        target_url = f'{DIFY_BASE_URL}/chat-messages'
        
        # 发送请求到Dify API
        response = requests.post(target_url, json=data, headers=headers)
        
        # 返回响应
        return jsonify(response.json()), response.status_code
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# # 通用代理接口，可以代理所有Dify API请求
# @app.route('/proxy/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
# def proxy_request(path):
#     try:
#         # 准备请求头，添加API Key
#         headers = request.headers.copy()
#         headers['Authorization'] = f'Bearer {API_KEY}'
#         
#         # 构建目标URL
#         target_url = f'{DIFY_BASE_URL}/{path}'
#         
#         # 准备请求数据
#         data = request.get_json() if request.is_json else None
#         
#         # 发送请求到Dify API
#         response = requests.request(
#             method=request.method,
#             url=target_url,
#             headers=headers,
#             json=data,
#             params=request.args
#         )
#         
#         # 返回响应
#         return jsonify(response.json()), response.status_code
#         
#     except Exception as e:
#         return jsonify({'error': str(e)}), 500
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)